package cuit.demo.controller;

import cuit.demo.Entity.Article;

import cuit.demo.Entity.Comment;
import cuit.demo.Entity.User;
import cuit.demo.service.MyService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Controller
public class HomepageController {

    @Autowired
    private MyService myService;

    @GetMapping("/personalhomepage")
    public String findselfarticle(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user!= null) {
            Integer userId = user.getUserid();
            List<Article> articles = myService.findArticlesByUserId(userId);
            if (articles!= null &&!articles.isEmpty()) {
                model.addAttribute("articles", articles);
            }
            return "personalhomepage";
        }
       else{
           return "login";
        }
    }

    @PostMapping("/personalhomepage/publish")
    public String publishArticle(
            @RequestParam("articleTitle") String articleTitle,
            @RequestParam("articleText") String articleText,
            @RequestParam("articleAttachment") MultipartFile articleAttachment,
            HttpSession session,
            Model model) {
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserid();
        if (userId!= null) {
            Article newArticle = new Article();
            newArticle.setArticle_title(articleTitle);
            newArticle.setArticle_text(articleText);
            newArticle.setArticle_time(String.valueOf(LocalDateTime.now()));
            newArticle.setUser_id(userId);
            newArticle.setArticler(user.getUsername());

            // 处理上传的附件
            if (!articleAttachment.isEmpty()) {
                try {
                    // 定义附件保存的路径为D:\attachment，你可根据实际情况修改
                    String uploadDir = "D:\\attachment";
                    Path uploadPath = Paths.get(uploadDir);
                    if (!Files.exists(uploadPath)) {
                        Files.createDirectories(uploadPath);
                    }

                    // 获取原始文件名
                    String originalFileName = articleAttachment.getOriginalFilename();
                    newArticle.setAttachment_name(originalFileName);

                    // 生成保存文件的完整路径
                    String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
                    String uniqueFileName = System.currentTimeMillis() + fileExtension;
                    Path filePath = uploadPath.resolve(uniqueFileName);

                    // 将文件保存到服务器
                    articleAttachment.transferTo(filePath.toFile());

                    // 设置文章实体中的附件路径
                    newArticle.setArticle_attachment(filePath.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("error", "附件上传失败，请检查以下可能的原因：");
                    model.addAttribute("errorDetail1", "1. 确保D盘存在且有足够的可用空间。");
                    model.addAttribute("errorDetail2", "2. 检查应用程序是否有写入D:\\attachment目录的权限。");
                    model.addAttribute("errorDetail3", "3. 文件可能已损坏或格式不被支持。");
                    return "redirect:/personalhomepage";
                }
            }

            // 保存文章，数据库会自动生成 article_id
            myService.saveArticle(newArticle);
            model.addAttribute("message", "文章发布成功！");
        } else {
            model.addAttribute("error", "用户未登录，无法发布文章。");
            return "redirect:/login";
        }
        return "redirect:/personalhomepage";
    }


    // 处理文章删除的方法
    @GetMapping("/personalhomepage/delete/{articleId}")
    public String deleteArticle(@PathVariable int articleId, Model model) {
        myService.deleteArticle(articleId);
        System.out.println(articleId);
        model.addAttribute("message", "文章删除成功！");
        return "redirect:/personalhomepage";
    }


}